/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * <p>Project: 209715200 (200MB)  10485760(10MB)
 * <p>Powered by webrx On 2022-03-11 11:32:25
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet("/upload")
@MultipartConfig(maxRequestSize = 209715200)
public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String n = "";
        boolean f = true;
        Part file = null;
        try {
            n = req.getParameter("user");
            file = req.getPart("fs");
            String filename = file.getSubmittedFileName().toString();

            //控制上传的格式(jpg,gif,png,rar,zip,pdf)
            Set<String> allow = new HashSet<>(List.of("jpg","zip"));
            String ext = filename.substring(filename.lastIndexOf(".")+1);
            if(!allow.contains(ext)){
                f = false;
                n = String.format("上传失败，不允许上的此(%s)",ext);
            }

            //控制上传的文件的大小 10485760 10MB
            long maxsize =  10485760;
            if(f) {
                if (file.getSize() >= maxsize) {
                    f = false;
                    n = String.format("上传失败，不允许上超出10MB的文件（%d）", file.getSize());
                }
            }

            //控制命名及位置
            //filename = UUID.randomUUID().toString().toLowerCase().concat(".").concat(ext);
            //filename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssS")).concat(".").concat(ext);

            //user.jpg  user.jpg  user(1).jpg  user(2).jpg

            //上的位置 /upload/user/202203 xxx
            //C:\\javaweb\\uploads\\target\\uploads-1.0\\upload\\user\\202203
            String path = req.getServletContext().getRealPath(String.format("/upload/user/%tY%<tm",System.currentTimeMillis()));
            File ff = new File(path);
            if(!ff.exists()) ff.mkdirs();

            file.write(String.format("%s/%s",path,filename));



        } catch (Exception e) {
            System.out.println(e.getMessage());
            n = "上传失败，太大了（不能超过10MB)";
            f= false;
        }
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\">");
        out.println("<title>玉灵 QQ:7031633 Email:webrx@126.com</title>");
        out.println("<meta name=\"keywords\" content=\"关键字\">");
        out.println("<meta name=\"description\" content=\"简介\">");
        out.println("</head>");
        out.println("<body>");

        out.printf("<h3>%s</h3>",n);
        if(f){
            out.printf("<h3>%s</h3>", file.getName());
            out.printf("<h3>%s</h3>", file.getSubmittedFileName());
            out.printf("<h3>%s</h3>", file.getSize());
            out.printf("<h3>%s</h3>", file.getContentType());
        }
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
}
